package sys

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
	"xkginweb/commons/response"
	"xkginweb/model/entity/sys"
)

type SysUserRolesApi struct{}

// 用户授权角色
func (api *SysUserRolesApi) SaveData(c *gin.Context) {
	// 1: 第一件事情就准备数据的载体
	roleIds, _ := c.GetQuery("roleIds")
	if roleIds == "" {
		// 如果参数注入失败或者出错就返回接口调用这。出错了.
		response.FailWithMessage("请选择授权的角色", c)
		return
	}

	roleIdsSplit := strings.Split(roleIds, ",")
	var sysUserRoles []*sys.SysUserRoles
	for _, roleId := range roleIdsSplit {
		parseUint, _ := strconv.ParseUint(roleId, 10, 64)
		sysUserRole := sys.SysUserRoles{}
		sysUserRole.UserId = c.GetUint("userId")
		sysUserRole.RoleId = uint(parseUint)
		sysUserRoles = append(sysUserRoles, &sysUserRole)
	}

	// 创建实例，保存帖子
	err := sysUserRolesService.SaveSysUserRoles(c.GetUint("userId"), sysUserRoles)
	// 如果保存失败。就返回创建失败的提升
	if err != nil {
		response.FailWithMessage("创建失败", c)
		return
	}
	// 如果保存成功，就返回创建创建成功
	response.Ok("创建成功", c)
}

/*
*
查询用户授权
*/
func (api *SysUserRolesApi) SelectUserRoles(c *gin.Context) {
	roles, _ := sysUserRolesService.SelectUserRoles(c.GetUint("userId"))
	response.Ok(roles, c)
}
